package com.gy.education.mine;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.gy.education.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2016/1/27.
 */
public class TakePhotoFramgment extends Fragment {

    private View layout;
    private Camera camera;
    private Camera.Parameters parameters = null;
    Bundle bundle = null; // 声明一个Bundle对象，用来存储数据
    private static String path;
    private int position;
    private Matrix matrix = new Matrix();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.activity_take_pic, null);

        // fragment传递过来的参数
        Bundle bundle = getArguments();
        position = bundle.getInt("position");

        SurfaceView surfaceView = (SurfaceView) view
                .findViewById(R.id.surfaceView);

        if(position == 101){
            Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(R.mipmap.icon_identity_front)).getBitmap();
            // 设置旋转角度
            matrix.setRotate(90);
            // 重新绘制Bitmap
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), matrix, true);

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(bitmap.getWidth(),bitmap.getHeight());
            surfaceView.setLayoutParams(params);
        }

        surfaceView.getHolder()
                .setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceView.getHolder().setFixedSize(176, 144); //设置Surface分辨率
        surfaceView.getHolder().setKeepScreenOn(true);// 屏幕常亮
        surfaceView.getHolder().addCallback(new SurfaceCallback());//为SurfaceView的句柄添加一个回调函数
        return view;
    }

    /**
     * 拍摄照片
     */
    public void takePic() {
        camera.takePicture(null, null, new MyPictureCallback());
    }


    private final class MyPictureCallback implements Camera.PictureCallback {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            try {
                bundle = new Bundle();
                bundle.putByteArray("bytes", data); //将图片字节数据保存在bundle当中，实现数据交换
                saveToSDCard(data); // 保存图片到sd卡中
                //                camera.startPreview(); // 拍完照后，重新开始预览
                Intent intent = new Intent(getActivity(), ShowActivity.class);
                intent.putExtras(bundle);
                intent.putExtra("path", path);
                intent.putExtra("position", position);
                if(position == 101){
                    startActivityForResult(intent,101);
                } else {
                    getActivity().setResult(101,intent);
                    getActivity().finish();
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 101){
            getActivity().finish();
        }
    }

    /**
     * 将拍下来的照片存放在SD卡中
     *
     * @param data
     * @throws IOException
     */
    public static void saveToSDCard(byte[] data) throws IOException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
        String filename = format.format(date) + ".png";
        File fileFolder = new File(Environment.getExternalStorageDirectory()
                + "/finger/");
        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录
            fileFolder.mkdir();
        }
        File jpgFile = new File(fileFolder, filename);
        path = jpgFile.getAbsolutePath();
        FileOutputStream outputStream = new FileOutputStream(jpgFile); // 文件输出流
        outputStream.write(data); // 写入sd卡中
        outputStream.close(); // 关闭输出流
    }


    private final class SurfaceCallback implements SurfaceHolder.Callback {

        // 拍照状态变化时调用该方法
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
            //            parameters = camera.getParameters(); // 获取各项参数
            //            parameters.setPictureFormat(PixelFormat.JPEG); // 设置图片格式
            //            parameters.setPreviewSize(width, height); // 设置预览大小
            //            parameters.setPreviewFrameRate(5);  //设置每秒显示4帧
            //            parameters.setPictureSize(width, height); // 设置保存的图片尺寸
            //            parameters.setJpegQuality(80); // 设置照片质量

            parameters = camera.getParameters();
            parameters.setPictureFormat(PixelFormat.JPEG);
            //            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//1连续对焦
            camera.setParameters(parameters);
            camera.startPreview();
            camera.cancelAutoFocus();

        }

        // 开始拍照时调用该方法
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                camera = Camera.open(); // 打开摄像头
                camera.setPreviewDisplay(holder); // 设置用于显示拍照影像的SurfaceHolder对象
                camera.setDisplayOrientation(getPreviewDegree(getActivity()));


                parameters = camera.getParameters();
                parameters.setPictureFormat(PixelFormat.JPEG);
                //                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//1连续对焦
                camera.setParameters(parameters);
                camera.startPreview();
                camera.cancelAutoFocus();

                camera.startPreview(); // 开始预览
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        // 停止拍照时调用该方法
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            if (camera != null) {
                camera.release(); // 释放照相机
                camera = null;
            }
        }
    }

    // 提供一个静态方法，用于根据手机方向获得相机预览画面旋转的角度
    public static int getPreviewDegree(Activity activity) {
        // 获得手机的方向
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degree = 0;
        // 根据手机的方向计算相机预览画面应该选择的角度
        switch (rotation) {
            case Surface.ROTATION_0:
                degree = 90;
                break;
            case Surface.ROTATION_90:
                degree = 0;
                break;
            case Surface.ROTATION_180:
                degree = 270;
                break;
            case Surface.ROTATION_270:
                degree = 180;
                break;
        }
        return degree;
    }
}
